package com.wolf.gulimall.order.listener;

import com.rabbitmq.client.Channel;
import com.wolf.common.to.mq.SeckillOrderTo;
import com.wolf.gulimall.order.entity.OrderEntity;
import com.wolf.gulimall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 秒杀队列监听器
 */
@Slf4j
@Component
@RabbitListener(queues = "order.seckill.order.queue")
public class OrderSeckillListener {
    @Autowired
    private OrderService orderService;
    @RabbitHandler
    public void listener(SeckillOrderTo seckillOrderTo, Channel channel, Message message) throws IOException {
        log.info("收到创建秒杀订单信息,准备创建秒杀订单:[{}] ", seckillOrderTo);
        try {
            orderService.createSeckillOrder(seckillOrderTo);
            //手动应答,确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("创建秒杀订单异常:",e);
            //重新回到队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
